<!--
 * @Author: liaoxing
 * @Date: 2022-01-04 14:09:26
 * @LastEditors: liaoxing
 * @LastEditTime: 2022-03-23 18:21:26
 * @Description: liaoxing created
 * @FilePath: \pin-xin-admin\src\views\business\quote\project.vue
-->
<template>
  <div class="quoteProject relative">
    <el-form :model="searchValue" ref="queryForm" :inline="true" label-width="80px" size="mini">
      <el-form-item label="项目名称">
        <el-input
          placeholder="请输入项目名称"
          clearable
          style="width: 200px"
          v-model="searchValue.projectName"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="tableData" border style="width: 100%">
      <el-table-column prop="projectName" label="项目名称"></el-table-column>
      <el-table-column prop="projectCode" label="项目标识"></el-table-column>
      <el-table-column prop="parameterBundleName" label="项目分类"></el-table-column>
      <el-table-column label="表达式配置">
        <template slot-scope="scope">
          <span
            v-if="scope.row.isNeedVariable"
            class="jstarfont jstar-bianji1 finger"
            @click="editItem(scope.$index)"
          ></span>
          <span v-else>{{ '--' }}</span>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="float: right;margin-top: 20px"
      :current-page.sync="pageNum"
      :page-size="pageSize"
      layout="total, prev, pager, next, jumper"
      :total="totalSize"
    ></el-pagination>
    <!--项目弹窗 -->
    <el-dialog title="表达式" :visible.sync="dialogVisible" width="65%">
      <div style="height: 500px" v-if="expressForm">
        <el-form :model="expressForm" :rules="expressRules" ref="expressForm" label-width="100px">
          <el-form-item label="表达式名称">
            <el-input v-model="expressForm.variableName" :disabled="true"></el-input>
          </el-form-item>

          <el-form-item label="表达式" prop="variableExpressText">
            <calculatorTag :calculatorList.sync="calculatorList" :dependencyList.sync="varTreeData" :chooseVariable.sync="chooseVariable" :propsInfo="varTreeProps" ref="calculatorTag" :editData="editData"></calculatorTag>

            
            <!-- <div class="flex expressBox">
              <div class="leftBox">
                <div class="dropBox" @dragover="allowDrop($event)" @drop="drop($event)">
                  <el-input
                    type="textarea"
                    :rows="16"
                    v-model="expressForm.variableExpressText"
                    resize="none"
                  ></el-input>
                </div>
                <div style="margin-top:20px">
                  <el-button type="primary" @click="checkExpress()">公式校验</el-button>
                </div>
              </div>
              <div class="rightBox">
                <div class="treeBox">
                  <el-tree :data="varTreeData" :props="varTreeProps" :default-expand-all="true">
                    <div
                      slot-scope="{ node, data }"
                      style="positon: absolute; z-index: 9999;"
                      :draggable="(data.isLeaf) ? 0 : 1"
                      @dragstart="drag($event, data)"
                    >
                      <span v-if="!data.isLeaf">{{ node.label }}</span>
                      <el-tag v-else>{{ node.label }}</el-tag>
                    </div>
                  </el-tree>
                </div>
              </div>
            </div> -->
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer">
        <el-button type="primary" @click="submitDefinition">确定提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import checkFormula from '@/utils/checkFormula'
import calculatorTag from '@/components/calculatorTag'
export default {
  name: 'quoteProject',
  components: {calculatorTag},
  data() {
    return {
      tableData: null,
      pageNum: 1,
      pageSize: 10,
      totalSize: 10,
      searchValue: {
        projectName: '',
      },
      dialogVisible: false,
      loading: false,
      expressForm: {},
      expressRules: {
        variableExpressText: [
          { required: true, message: '请输入表达式', trigger: 'blur' },
        ],
      },
      currentIndex: null,
      /* 公式 */
      chooseVariable: null,
      chooseKey: null,
      botTreeList: [
        {
          children: [],
          isLeaf: 0,
          key: '969396777',
          title: '系统参数',
        },
      ],
      varTreeData: [],
      varTreeProps: {
        children: 'children',
        label: 'title',
      },
      calcHtmlList: [],
      calculatorList: [{type: false}],
      editData: null
    }
  },
  async created() {
    await this.getParamsList()
    await this.getBotParam()
    await this.getParam()
  },
  watch: {
    pageNum: {
      deep: true,
      handler: function () {
        this.getParamsList()
      },
    },
    dialogVisible (value) {
      if (!value) {
        let timeOut = setTimeout(() => {
          window.clearTimeout(timeOut)
          this.calculatorList = [{type: false}]
        }, 200)
        this.$refs.calculatorTag.currentIndex = null
      }
    },
    // 'expressForm.variableExpressText': {
    //   deep: true,
    //   handler(value) {
    //     let newList = JSON.parse(JSON.stringify(this.calcHtmlList))
    //     this.expressForm.variableExpress = checkFormula.transformKey(
    //       value,
    //       newList.reverse()
    //     )
    //   },
    // },
  },
  methods: {
    editItem(index) {
      this.currentIndex = index
      const { variableName, variableExpress, variableExpressText, argumentsText } = this.tableData[index]

      this.editData = this.tableData[index]
      // let temp = []

      // if (this.tableData[index].arguments && this.tableData[index].arguments.length) {
      //   this.tableData[index].arguments.forEach((item, index) => {
      //     let tempObj = {
      //       key: item,
      //       title: argumentsText[index]
      //     }
      //     temp.push(tempObj)
      //   })
      //   console.log(temp)
      //   temp.forEach(it => {
      //     if (!it.title) return
      //     let index = this.calcHtmlList.findIndex(
      //       (item) => item.title.length >= it.title.length
      //     )
      //     if (index > -1) {
      //       this.calcHtmlList.splice(index, 0, it)
      //     } else {
      //       this.calcHtmlList.push(it)
      //     }
      //   })
      // }
      
      if (variableExpress && variableExpressText) {
        let calcList = variableExpress.trim().split(' ')
        let calcListText = variableExpressText.trim().split(' ')
        let tempList = []
        let newCalcList = calcList.filter(item => item != "")
        let newCalcListText = calcListText.filter(item => item != "")
        // console.log(newCalcList, newCalcListText)
        // console.log(calcList, calcListText)
        newCalcList.forEach((item, index) => {
          // console.log(index, item, calcListText[index])
          const temp = {}
          temp['key'] = item
          temp['title'] = newCalcListText[index]
          tempList.push({type: true, data: temp})
          tempList.push({type: false})
        })
        this.calculatorList = this.calculatorList.concat(tempList)
      }
      

      let tempCalc = { variableExpress, variableName, variableExpressText }
      // temp.variableExpressText = '' 
      this.expressForm = tempCalc
      this.dialogVisible = true
    },
    handleQuery() {
      this.getParamsList()
    },
    resetQuery() {
      this.searchValue.projectName = null
      this.handleQuery()
    },
    submitDefinition() {
      let temp = JSON.parse(JSON.stringify(this.tableData[this.currentIndex]))
      // temp.variableExpress = this.expressForm.variableExpress

      // let newList = JSON.parse(JSON.stringify(this.calcHtmlList))
      // console.log(checkFormula.transformKey(
      //   this.expressForm.variableExpressText,
      //   newList.reverse()
      // ))

      temp.variableExpress = this.$refs.calculatorTag.calculator
      temp.variableExpressText = this.$refs.calculatorTag.calculatorText

      let params = {
        id: temp.id,
        params: temp,
      }

      console.log(params)

      this.$params
        .editChargingItemExpenses(params)
        .then((res) => {
          if (res.code === 200) {
            this.$message.success('提交成功')
            this.dialogVisible = false
            this.getParamsList()
          } else {
            this.$message.error(res.code + '-' + res.msg)
          }
          this.loading = false
        })
        .catch((e) => {
          this.$message.error(e.toString())
        })
    },
    /* 获取项目列表 */
    getParamsList() {
      return new Promise((resolve) => {
        this.loading = true
        let params = {
          pn: this.pageNum,
          ps: this.pageSize,
          projectName: this.searchValue.projectName,
        }
        if (!this.searchValue.projectName) {
          delete params.projectName
        }

        this.$params
          .queryChargingItemExpenses(params)
          .then((res) => {
            if (res.code === 200) {
              this.tableData = res.data.rows
              this.totalSize = res.data.total * 1
            } else if (res.code === 500) {
              this.tableData = []
              this.$message.info('项目为空！')
            } else {
              this.$message.error(res.code + '-' + res.msg)
            }
            this.loading = false
            resolve()
          })
          .catch((e) => {
            this.$message.error(e.toString())
          })
      })
    },
    /* 元素放置 */
    // allowDrop(ev) {
    //   ev.preventDefault()
    // },
    // drop(ev) {
    //   ev.preventDefault()
    //   if (!this.expressForm.variableExpressText) {
    //     this.expressForm.variableExpressText = ''
    //   }
    //   this.expressForm.variableExpressText += ` ${this.chooseVariable.title || ''} `
    //   let index = this.calcHtmlList.findIndex(
    //     (item) => item.title.length >= this.chooseVariable.title.length
    //   )
    //   if (index > -1) {
    //     this.calcHtmlList.splice(index, 0, this.chooseVariable)
    //   } else {
    //     this.calcHtmlList.push(this.chooseVariable)
    //   }
    // },
    // drag(ev, info) {
    //   this.chooseVariable = info //拖过去的name
    //   this.chooseKey = info.key //拖过去的key
    // },
    /* 获取参数 */
    getParam() {
      return new Promise((resolve) => {
        this.$params
          .queryDictionaryAsTree()
          .then((res) => {
            if (res.code == 200) {
              this.varTreeData = this.botTreeList.concat(res.data)
              resolve()
            } else {
              this.$message.error(res.code + '-' + res.msg)
            }
            this.loading = false
          })
          .catch((err) => {
            this.$message.error(JSON.stringify(err))
          })
      })
    },
    getBotParam() {
      return new Promise((resolve) => {
        this.$params
          .queryDictionaryAsList({ pn: 1, ps: 9999, parameterType: 'BOT' })
          .then((res) => {
            if (res.code == 200) {
              res.data.rows.forEach((item) => {
                let temp = {
                  children: [],
                  isLeaf: 1,
                  key: item.parameterCode,
                  title: item.parameterName,
                }
                this.botTreeList[0].children.push(temp)
              })
            } else {
              this.$message.error(res.code + '-' + res.msg)
            }
            resolve()
          })
          .catch((err) => {
            this.$message.error(JSON.stringify(err))
          })
      })
    },
    /* 校验公式 */
    checkExpress() {
      let temp = []
      this.calcHtmlList.forEach((item) => {
        temp.push(item.key)
      })
      let params = {
        arguments: temp,
        calculator: this.expressForm.variableExpress,
      }
      this.$params
        .checkFormula(params)
        .then((res) => {
          if (res.code === 200) {
            this.$message.success('校验通过')
          } else {
            this.$message.error(res.code + '-' + res.msg)
          }
        })
        .catch((e) => {
          this.$message.error(e.toString())
        })
    },
  },
}
</script>

<style lang="less">
.quoteProject {
  width: 100%;
  height: calc(100vh - 84px);
  box-sizing: border-box;
  padding: 16px;
  .expressBox {
    .leftBox {
      width: 440px;
      height: 100%;
      .inputBox {
        margin-top: 20px;
        height: 190px;
        width: 100%;
        overflow: auto;
      }
    }
    .rightBox {
      margin-left: 30px;
      width: 220px;
      height: 270px;
      .treeBox {
        height: 100%;
        width: 100%;
        .el-tree {
          height: 260px;
          overflow: auto;
        }
      }
    }
  }
}
</style>